﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Drawing.Drawing2D;

namespace nsWeldController
{
    public partial class DockMain : DockContent
    {
        private CLog mLog = CWeldController.mLog;

        public DockMain()
        {
            InitializeComponent();
        }

        private string GetCylinderStateFromByte(byte bt)
        {
            string res = "";
            switch (bt)
            {
                case 0:
                    res = "停止";
                    break;

                case 1:
                    res = "伸出中";
                    break;

                case 2:
                    res = "拉回中";
                    break;

                case 3:
                    res = "伸出";
                    break;

                case 4:
                    res = "拉回";
                    break;

                default:
                    res = "未知";
                    break;
            }
            return res;
        }

        private string GetMotorStateFromByte(byte bt)
        {
            string res = "";
            switch (bt)
            {
                case 0:
                    res = "停止";
                    break;

                case 1:
                    res = "正向";
                    break;

                case 2:
                    res = "负向";
                    break;

                case 3:
                    res = "异常";
                    break;

                default:
                    res = "未知";
                    break;
            }
            return res;
        }

        /// <summary>
        /// 将控制板返回的信息显示到主界面上
        /// </summary>
        public void ShowMashineInfo()
        {
            txtCoordinateX.Text = CWeldController.mMashineInfo.x.ToString();
            txtCoordinateY.Text = CWeldController.mMashineInfo.y.ToString();
            txtCoordinateZ.Text = CWeldController.mMashineInfo.z.ToString();
            txtCoordinateR.Text = CWeldController.mMashineInfo.revolveMotorPos.ToString();
            txtOriginX.Text = CWeldController.mMashineInfo.originX.ToString();
            txtOriginY.Text = CWeldController.mMashineInfo.originY.ToString();
            txtOriginZ.Text = CWeldController.mMashineInfo.originZ.ToString();
            txtStatL.Text = GetMotorStateFromByte(CWeldController.mMashineInfo.statLineMotor);
            txtStatCz.Text = GetCylinderStateFromByte(CWeldController.mMashineInfo.statCz);
            txtStatC1.Text = GetCylinderStateFromByte(CWeldController.mMashineInfo.statC1);
            txtStatC2.Text = GetCylinderStateFromByte(CWeldController.mMashineInfo.statC2);
            txtStatC3.Text = GetCylinderStateFromByte(CWeldController.mMashineInfo.statC3);
            txtStaGumPointer.Text = CWeldController.mMashineInfo.statGumPointer == 0 ? "关闭" : "打开";
            txtStatWeldPointer.Text = CWeldController.mMashineInfo.statWeldPointer == 0 ? "关闭" : "打开";
            txtStatBatteryCatcher.Text = CWeldController.mMashineInfo.statBatteryCatcher == 0 ? "无" : "有";
            txtStatX.Text = GetMotorStateFromByte(CWeldController.mMashineInfo.statX);
            txtStatY.Text = GetMotorStateFromByte(CWeldController.mMashineInfo.statY);
            txtStatZ.Text = GetMotorStateFromByte(CWeldController.mMashineInfo.statZ);
            txtRunningState.Text = CWeldController.mMashineInfo.iRunningFlag == 0 ? "停止" : "运行";
            txtPauseState.Text = CWeldController.mMashineInfo.iPausedFlag == 0 ? "继续" : "暂停";
            // 查询到的系统状态是暂停的话，自动控制的按钮显示为继续
            if (txtPauseState.Text == "暂停")
            {
                btnAutoPause.Text = "继续";
                btnAutoPause.Image = Properties.Resources.resume;
            }
            else
            {
                btnAutoPause.Text = "暂停";
                btnAutoPause.Image = Properties.Resources.pause;
            }
            txtIsProcessing.Text = CWeldController.mMashineInfo.iProcessingFlag == 0 ? "无" : "有";
            txtBoardCount.Text = mBoardCount.ToString();
            int index = CWeldController.mMashineInfo.currentStep;
            if (index >= 0 && index < CWeldController.mDockSetParameter.dgvAutoGumList.Rows.Count
                && CWeldController.mMashineInfo.iRunningFlag == 1)
            {
                CWeldController.mDockSetParameter.dgvAutoGumList.ClearSelection();
                CWeldController.mDockSetParameter.dgvAutoGumList.Rows[index].Selected = true;
                CWeldController.mDockSetParameter.dgvAutoGumList.CurrentCell = CWeldController.mDockSetParameter.dgvAutoGumList.SelectedCells[0];
            }
        }

        private void btnAutoGumStop_Click(object sender, EventArgs e)
        {
            GumCommandStop();
        }

        private void btnAutoGumBegin_Click(object sender, EventArgs e)
        {
            GumCommandStart();
        }

        private void btnAutoGumPause_Click(object sender, EventArgs e)
        {
            if (btnAutoPause.Text == "暂停")
            {
                GumCommandPause();
                btnAutoPause.Text = "继续";
                btnAutoPause.Image = Properties.Resources.resume;
            }
            else
            {
                GumCommandResume();
                btnAutoPause.Text = "暂停";
                btnAutoPause.Image = Properties.Resources.pause;
            }
        }

        private void btnAutoGumAbord_Click(object sender, EventArgs e)
        {
            GumCommandAbord();
        }

        private void btnSysReset_Click(object sender, EventArgs e)
        {
            SysRestCommand(1);
        }

        private void EnQueueSend(ET_GPES_SENDMSG stSend)
        {
            CWeldController.mDockSerialProtocol.EnQueueSend(stSend);
        }

        /// <summary>
        /// 点胶枪控制命令
        /// </summary>
        /// <param name="bt">
        /// 0：停止
        /// 1：开始
        /// 2：暂停
        /// 3：继续
        /// 4：取消
        /// </param>
        private void GumCommandStart()
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_START;
            stSend.sendMsg = new byte[1] { 1 };
            EnQueueSend(stSend);
        }

        private void GumCommandPause()
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_PAUSE;
            stSend.sendMsg = new byte[1] { 1 };
            EnQueueSend(stSend);
        }

        private void GumCommandResume()
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_RESUME;
            stSend.sendMsg = new byte[1] { 1 };
            EnQueueSend(stSend);
        }

        private void GumCommandAbord()
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_ABORD;
            stSend.sendMsg = new byte[1] { 1 };
            EnQueueSend(stSend);
        }

        private void GumCommandStop()
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_STOP;
            stSend.sendMsg = new byte[1] { 1 };
            EnQueueSend(stSend);
        }

        private void SysRestCommand(byte command)
        {
            ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
            stSend.CLA = (byte)CLA.CLA_CTRL;
            stSend.INS = (byte)INS.CMD_RESET;
            stSend.sendMsg = new byte[1] { command };
            EnQueueSend(stSend);
        }

        private void chkIsBeginQuery_CheckedChanged(object sender, EventArgs e)
        {
            if (chkIsBeginQuery.Checked)
            {
                CWeldController.mDockSerialProtocol.BeginQueryThread();
            }
            else
            {
                CWeldController.mDockSerialProtocol.AbordQueryThread();
            }
        }

        private void txtCoordinateX_TextChanged(object sender, EventArgs e)
        {
            drawActions.SetCurrentPoint((int)(CWeldController.mMashineInfo.x + CWeldController.mMashineInfo.originX), (int)(CWeldController.mMashineInfo.y + CWeldController.mMashineInfo.originY));
            DrawAction();
        }

        private void txtCoordinateY_TextChanged(object sender, EventArgs e)
        {
            drawActions.SetCurrentPoint((int)(CWeldController.mMashineInfo.x + CWeldController.mMashineInfo.originX), (int)(CWeldController.mMashineInfo.y + CWeldController.mMashineInfo.originY));
            DrawAction();
        }

        private void drawArea_SizeChanged(object sender, EventArgs e)
        {
            DrawAction();
        }

        /// <summary>
        /// 将Actions中的动作绘制的DrawArea上
        ///  非插补移动用虚线，插补移动用实线
        ///  点胶开启使用黄色 Z轴压下线条宽度加倍
        ///  绿色圆圈为原点位置
        /// </summary>
        public void DrawAction()
        {
            drawActions.DrawAll(CWeldController.mDockSetParameter.mAutoActionList);
            Invalidate(true);
        }

        private DateTime mDataTime = new DateTime();
        private int mBoardCount;        // 用于工件计数，每当控制返回的currentStep==-1时加1
        private bool mIsBoardCountAdd;  // 用于控制currentStep==-1时只加1一次
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (txtRunningState.Text != "运行"
                || txtPauseState.Text != "继续")
            {
                return;
            }

            DateTime dataTime = new DateTime();
            dataTime = DateTime.Now;
            TimeSpan timeSpan = new TimeSpan();
            timeSpan = dataTime - mDataTime;
            txtRuntimes.Text = timeSpan.ToString(@"hh\:mm\:ss");

            int index = CWeldController.mMashineInfo.currentStep;
            if (index == -1)
            {
                if (!mIsBoardCountAdd)
                {
                    mBoardCount++;
                    mIsBoardCountAdd = true;
                }
            }
            else
            {
                mIsBoardCountAdd = false;
            }
        }

        /// <summary>
        /// 状态变为运行后的处理
        ///  重新开始计时和工件计数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtRunningState_TextChanged(object sender, EventArgs e)
        {
            if (txtRunningState.Text == "运行")
            {
                timer1.Enabled = true;
                txtRuntimes.Text = "";
                mDataTime = DateTime.Now;
                txtBoardCount.Text = "";
                mBoardCount = 0;
            }
        }
    }
}
